package com.qiantu.phone.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewConfiguration;

import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;

public class WindSpeedSeekBar extends View {

    private float mTouchDownX;
    private int mScaledTouchSlop;
    private Drawable windSpeedBarOpenThumb;
    private Drawable windSpeedBarCloseThumb;
    private float windSpeedTotalStep;
    // 画笔
    private Paint mPaint;
    private Paint mThumbPaint;
    private float windSpeedBarHeight;
    private float windSpeedBarThumbHeight;
    private float windSpeedBarThumbShadowSize;
    private float canSlideTotalWidth;
    private OnSeekBarChangeListener mOnSeekBarChangeListener;
    private float thumbCx;
    private RectF mBarRectF;
    private RectF mLineRectF;
    private boolean isOpen = false;
    private int shadowOffsetX;
    private int shadowOffsetY;
    private int mStep;
    private float lineHeight;
    private int lineWidth;
    private float mStepWidth;
    private boolean hasMove = false;
    private float currentDistance;
    private boolean inBar;
    private float slidDistance;
    private int windSpeedBarBgColor;

    public WindSpeedSeekBar(Context context) {
        this(context, null);
    }

    public WindSpeedSeekBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WindSpeedSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = attrs == null ? null : getContext().obtainStyledAttributes(attrs, R.styleable.WindSpeedSeekBar);
        if (ta != null) {
            windSpeedTotalStep = ta.getInt(R.styleable.WindSpeedSeekBar_wind_speed_total_step, 3);
            windSpeedBarHeight = ta.getDimension(R.styleable.WindSpeedSeekBar_wind_speed_bar_height, dp2px(26));
            windSpeedBarThumbHeight = ta.getDimension(R.styleable.WindSpeedSeekBar_wind_speed_bar_thumb_height, dp2px(40));
            lineHeight = ta.getDimension(R.styleable.WindSpeedSeekBar_wind_speed_bar_line_height, dp2px(7));
            windSpeedBarThumbShadowSize = ta.getDimension(R.styleable.WindSpeedSeekBar_wind_speed_bar_thumb_shadow_size, dp2px(4));
            windSpeedBarOpenThumb = ta.getDrawable(R.styleable.WindSpeedSeekBar_wind_speed_bar_open_thumb);
            windSpeedBarCloseThumb = ta.getDrawable(R.styleable.WindSpeedSeekBar_wind_speed_bar_close_thumb);
            windSpeedBarBgColor = ta.getColor(R.styleable.WindSpeedSeekBar_wind_speed_bar_bg_color, AppApplication.getInstance().getThemeColor(R.attr.secondaryColor9));
        }
        mScaledTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mBarRectF = new RectF();
        mLineRectF = new RectF();
        shadowOffsetX = getResources().getDimensionPixelSize(R.dimen.dp_1);
        shadowOffsetY = getResources().getDimensionPixelSize(R.dimen.dp_1);
        lineWidth = getResources().getDimensionPixelSize(R.dimen.dp_1);
        init();
    }

    private void init() {
        mPaint = new TextPaint();
        mPaint.setAntiAlias(true);

        mThumbPaint = new Paint();
        mThumbPaint.setAntiAlias(true);
        mThumbPaint.setShadowLayer(windSpeedBarThumbShadowSize, shadowOffsetX, shadowOffsetY, 0x33474646);
    }

    public void setWindSpeedBarOpenCloseThumb(int windSpeedBarOpenThumb, int windSpeedBarCloseThumb) {
        this.windSpeedBarOpenThumb = AppApplication.getInstance().getThemeDrawable(windSpeedBarOpenThumb);
        this.windSpeedBarCloseThumb = AppApplication.getInstance().getThemeDrawable(windSpeedBarCloseThumb);
        invalidate();
    }

    public void setWindSpeedTotalStep(float windSpeedTotalStep) {
        this.windSpeedTotalStep = windSpeedTotalStep;
        invalidate();
    }

    public void setLineHeight(float lineHeight) {
        this.lineHeight = lineHeight;
        invalidate();
    }

    public void setWindSpeedBarHeight(float windSpeedBarHeight) {
        this.windSpeedBarHeight = windSpeedBarHeight;
        invalidate();
    }

    public void setWindSpeedBarThumbHeight(float windSpeedBarThumbHeight) {
        this.windSpeedBarThumbHeight = windSpeedBarThumbHeight;
        invalidate();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) {
            return false;
        }
        float distance = 0;
        float barRadius = windSpeedBarThumbHeight / 2f;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                hasMove = false;
                mTouchDownX = event.getX();
                //只有Thumb区域可以点击拖动
                if (mTouchDownX > thumbCx - barRadius && mTouchDownX < thumbCx + barRadius) {
                    inBar = true;
                    if(mStep == 0){
                        slidDistance = windSpeedBarThumbShadowSize + barRadius;
                    }else if(mStep == windSpeedTotalStep - 1){
                        slidDistance = mStep * mStepWidth + windSpeedBarThumbShadowSize - barRadius;
                    }else{
                        slidDistance = mStep * mStepWidth + windSpeedBarThumbShadowSize;
                    }
                 } else {
                    inBar = false;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (!isOpen) {
                    return true;
                }
                if(inBar){
                    distance = event.getX() - mTouchDownX + slidDistance;
                    getParent().requestDisallowInterceptTouchEvent(true);
                    Log.i("luzx", "Math.abs(distance) > mScaledTouchSlop:" + Math.abs(distance) + ">=" + mScaledTouchSlop);
                    if (currentDistance != distance) {
                        hasMove = true;
                        currentDistance = distance;
                        currentDistance = currentDistance > getWidth() - barRadius - windSpeedBarThumbShadowSize ? getWidth() - barRadius - windSpeedBarThumbShadowSize : currentDistance;
                        currentDistance = currentDistance < barRadius + windSpeedBarThumbShadowSize ? barRadius + windSpeedBarThumbShadowSize : currentDistance;
//                    calculateStep(distance + slidDistance);
                        Log.i("luzx", "currentDistance:" + currentDistance);
                        invalidate();
                        if (mOnSeekBarChangeListener != null) {
                            mOnSeekBarChangeListener.onValueChanged(mStep);
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                //关闭状态不触发
                if (!isOpen) {
                    return true;
                }
                //点击
                float upX = event.getX();
                if(!hasMove){
                    currentDistance = upX;
                }
                hasMove = false;
                getParent().requestDisallowInterceptTouchEvent(true);
                Log.i("luzx", "Math.abs(distance) > mScaledTouchSlop:" + Math.abs(distance) + ">=" + mScaledTouchSlop);
                calculateStep();
                Log.i("luzx", "mStep:" + mStep);
                invalidate();
                getParent().requestDisallowInterceptTouchEvent(false);
                if (mOnSeekBarChangeListener != null) {
                    playSoundEffect(SoundEffectConstants.CLICK);
                    mOnSeekBarChangeListener.onValueChanged(mStep);
                }
//                setAlpha(1f);
                break;
            case MotionEvent.ACTION_CANCEL:
//                getParent().requestDisallowInterceptTouchEvent(false);
//                if (mOnSeekBarChangeListener != null) {
//                    mOnSeekBarChangeListener.onStopTrackingTouch(progressStep100);
//                }
//                setAlpha(1f);
                break;
        }
        return true;
    }

    private void calculateStep() {
        float temp = (currentDistance - windSpeedBarThumbShadowSize) / mStepWidth;
        int step = (int) temp;
        float offset = temp - step;
        if (offset == 0) {
            mStep = step;
        } else {
            if (offset * mStepWidth >= mStepWidth / 2f) {
                mStep = step + 1;
            } else {
                mStep = step;
            }
        }
        mStep = mStep < 0 ? 0 : mStep;
        mStep = mStep > windSpeedTotalStep - 1 ? (int) (windSpeedTotalStep - 1) : mStep;
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        Log.i("luzx", "WindSpeedSeekBar onDraw");
        mPaint.setColor(windSpeedBarBgColor);
        if (hasMove) {
            thumbCx = currentDistance;
        } else {
            if (mStep == 0) {
                thumbCx = windSpeedBarThumbShadowSize + windSpeedBarThumbHeight / 2f;
            } else if (mStep == windSpeedTotalStep - 1) {
                thumbCx = getWidth() - windSpeedBarThumbShadowSize - windSpeedBarThumbHeight / 2f;
            } else {
                thumbCx = windSpeedBarThumbShadowSize + mStep * mStepWidth;
            }
        }
        canvas.drawRoundRect(mBarRectF, windSpeedBarHeight, windSpeedBarHeight, mPaint);
        for (int i = 1; i < windSpeedTotalStep - 1; i++) {
            float x = windSpeedBarThumbShadowSize + i * mStepWidth;
            mLineRectF.left = x - lineWidth / 2f;
            mLineRectF.right = mLineRectF.left + lineWidth;
            mPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor6));
            canvas.drawRect(mLineRectF, mPaint);
        }
        if (isOpen) {
            mThumbPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
            canvas.drawCircle(thumbCx, mBarRectF.top + windSpeedBarHeight / 2f, windSpeedBarThumbHeight / 2f, mThumbPaint);
            if (windSpeedBarOpenThumb != null) {
                windSpeedBarOpenThumb.setBounds((int) (thumbCx - windSpeedBarOpenThumb.getIntrinsicWidth() / 2f), (int) (mBarRectF.top + windSpeedBarHeight / 2f - windSpeedBarOpenThumb.getIntrinsicHeight() / 2f), (int) (thumbCx + windSpeedBarOpenThumb.getIntrinsicWidth() / 2f), (int) (mBarRectF.top + windSpeedBarHeight / 2f + windSpeedBarOpenThumb.getIntrinsicHeight() / 2f));
                windSpeedBarOpenThumb.draw(canvas);
            }
        } else {
            mThumbPaint.setColor(0xffffffff);
            canvas.drawCircle(thumbCx, mBarRectF.top + windSpeedBarHeight / 2f, windSpeedBarThumbHeight / 2f, mThumbPaint);
            if (windSpeedBarCloseThumb != null) {
                windSpeedBarCloseThumb.setBounds((int) (thumbCx - windSpeedBarCloseThumb.getIntrinsicWidth() / 2f), (int) (mBarRectF.top + windSpeedBarHeight / 2f - windSpeedBarCloseThumb.getIntrinsicHeight() / 2f), (int) (thumbCx + windSpeedBarCloseThumb.getIntrinsicWidth() / 2f), (int) (mBarRectF.top + windSpeedBarHeight / 2f + windSpeedBarCloseThumb.getIntrinsicHeight() / 2f));
                windSpeedBarCloseThumb.draw(canvas);
            }
        }
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int dw = getMeasuredWidth();
        int dh = (int) (Math.max(windSpeedBarHeight, windSpeedBarThumbHeight) + windSpeedBarThumbShadowSize * 2);
        setMeasuredDimension(dw, dh);
        mBarRectF.left = windSpeedBarThumbShadowSize;
        mBarRectF.right = dw - windSpeedBarThumbShadowSize;
        mBarRectF.top = windSpeedBarHeight > windSpeedBarThumbHeight ? windSpeedBarThumbShadowSize : (windSpeedBarThumbHeight - windSpeedBarHeight) / 2f + windSpeedBarThumbShadowSize;
        mBarRectF.bottom = mBarRectF.top + windSpeedBarHeight;
        canSlideTotalWidth = mBarRectF.right - mBarRectF.left;
        mStepWidth = canSlideTotalWidth / (windSpeedTotalStep - 1);
        mLineRectF.left = 0;
        mLineRectF.right = 0;
        mLineRectF.top = windSpeedBarThumbShadowSize + Math.max(windSpeedBarHeight, windSpeedBarThumbHeight) / 2f - lineHeight / 2f;
        mLineRectF.bottom = mLineRectF.top + lineHeight;
    }

    public void setStep(int step) {
        mStep = step;
        invalidate();
    }

    public int getStep() {
        return mStep;
    }

    public void setOpenState(boolean openState) {
        if (isOpen == openState) {
            return;
        }
        isOpen = openState;
        invalidate();
    }

    /**
     * 进度监听
     */
    public interface OnSeekBarChangeListener {
        /**
         * 进度监听回调
         *
         * @param step 进度
         */
        void onValueChanged(int step);
    }

    public void setOnSeekBarChangeListener(OnSeekBarChangeListener changeListener) {
        this.mOnSeekBarChangeListener = changeListener;
    }

    /**
     * dp转px
     *
     * @param dp dp值
     * @return px值
     */
    public int dp2px(float dp) {
        return (int) (getResources().getDimension(R.dimen.dp_1) * dp);
    }
}
